package com.huohuzhihui.web.controller.merchant;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import com.huohuzhihui.common.config.RuoYiConfig;
import com.huohuzhihui.common.constant.UserConstants;
import com.huohuzhihui.common.core.domain.entity.SysDept;
import com.huohuzhihui.common.core.domain.entity.SysUser;
import com.huohuzhihui.common.core.domain.model.LoginUser;
import com.huohuzhihui.common.exception.file.InvalidExtensionException;
import com.huohuzhihui.common.utils.SecurityUtils;
import com.huohuzhihui.common.utils.ServletUtils;
import com.huohuzhihui.common.utils.StringUtils;
import com.huohuzhihui.common.utils.file.FileUploadUtils;
import com.huohuzhihui.common.utils.file.MimeTypeUtils;
import com.huohuzhihui.framework.web.service.TokenService;
import com.huohuzhihui.merchant.domain.AgentCost;
import com.huohuzhihui.merchant.service.IAgentCostService;
import com.huohuzhihui.system.domain.CloudStorage;
import com.huohuzhihui.system.service.ISysDeptService;
import com.huohuzhihui.system.util.QiNiuFileOptUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.huohuzhihui.common.annotation.Log;
import com.huohuzhihui.common.core.controller.BaseController;
import com.huohuzhihui.common.core.domain.AjaxResult;
import com.huohuzhihui.common.enums.BusinessType;
import com.huohuzhihui.merchant.domain.MerMerchant;
import com.huohuzhihui.merchant.service.IMerMerchantService;
import com.huohuzhihui.common.utils.poi.ExcelUtil;
import com.huohuzhihui.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 商户Controller
 *
 * @author zylu
 * @date 2020-11-14
 */
@RestController
@RequestMapping("/merchant/merchant")
public class MerMerchantController extends BaseController {
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IAgentCostService agentCostService;

    /**
     * 获取商户列表
     */
    @GetMapping("/list")
    public AjaxResult list(SysDept dept) {
        dept.setDeptType(2);
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 查询商户列表（排除节点）
     */
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据商户编号获取详细信息
     */
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 获取商户下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }


    /**
     * 新增商户
     */
    @Log(title = "商户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept, HttpServletRequest request) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("新增商户'" + dept.getDeptName() + "'失败，商户名称已存在");
        }

        //设置上级部门为当前登陆用户
        LoginUser loginUser = tokenService.getLoginUser(request);
        SysUser sysUser = loginUser.getUser();

        dept.setParentId(sysUser.getDeptId());
        //部门类型=2为商户
        dept.setDeptType(2);
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改商户
     */
    @Log(title = "商户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("修改商户'" + dept.getDeptName() + "'失败，商户名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return AjaxResult.error("修改商户'" + dept.getDeptName() + "'失败，上级商户不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return AjaxResult.error("该商户包含未停用的下级商户！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除商户
     */
    @Log(title = "商户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return AjaxResult.error("存在下级商户,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.error("存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 查询商户抖音信息
     */
    @GetMapping(value = "getMerDouyin/{{deptId}}")
    public AjaxResult getMerDouyin(@PathVariable Long deptId) {

        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 充值
     */
    @GetMapping("/recharge")
    public AjaxResult recharge(SysDept dept) {
        //只查询当前商户的
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        SysDept agent = deptService.selectDeptById(sysUser.getDeptId());
        if (agent.getDeptType() != 1) {
            return AjaxResult.error("只允许代理商给商户进行充值");
        }

        int videoCount = dept.getVideoCount();

        //判断代理商余额是否充足
        if (videoCount > agent.getVideoCount()) {
            return AjaxResult.error("代理商余额不足，请联系平台充值");
        }

        //代理商扣除相应额度
        int ret = deptService.minusVideoCount(agent.getDeptId(), videoCount);

        if (ret == 1) {
            //给商户增加额度
            deptService.rechargeVideoCount(dept.getDeptId(), videoCount);

            //插入代理商消费记录
            AgentCost agentCost = new AgentCost();
            agentCost.setAgentId(agent.getDeptId());
            agentCost.setVideoCount(videoCount);
            agentCost.setCreateBy(sysUser.getUserName());
            agentCostService.insertAgentCost(agentCost);

            return AjaxResult.success(1);
        }
        return AjaxResult.error("充值失败");
    }

    /**
     * 上传商家视频
     */
    @Log(title = "上传商家视频", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadVideo")
    public AjaxResult uploadVideo(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            String videoUrl = null;
            try {
                videoUrl = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file, MimeTypeUtils.MEDIA_EXTENSION);
            } catch (InvalidExtensionException e) {
                e.printStackTrace();
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("videoUrl", videoUrl);
            // 更新缓存用户头像
            return AjaxResult.success("商家视频上传成功", videoUrl);
        }
        return AjaxResult.error("视频不能为空");
    }


    /**
     * 获取商户我的账户
     */
    @GetMapping("/myMerchant")
    public AjaxResult myMerchant(SysDept dept) {
        //只查询当前商户的
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();

        dept.setDeptId(sysUser.getDeptId());
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

}
